/*
 * Copyright (C) 2013 'Chaos'.Personal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.silly.adapter;

import com.silly.adapter.cache.CacheTypeHelper;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/**
 * Adapter中每一个Item的映射
 * 
 * @author Chaos
 * @date 2013-7-5
 * 
 */
public abstract class SillyAdapter extends BaseAdapter {

	private CacheTypeHelper mHelper = null;

	private boolean isMultipleType;

	public SillyAdapter() {
		/**
		 * 初始化ViewCache
		 */
		mHelper = new CacheTypeHelper();
	}
    
	/**
	 * 设置为多种不同的Type
	 */
	protected void setMultipleType(boolean isMultiple){
	    isMultipleType = isMultiple;	
	}
	
	@Override
	public final View getView(int position, View convertView, ViewGroup parent) {

		if (isMultipleType) {
			// 如果存在不一样的Type
			int type = getItemViewType(position);

			if (convertView != null && mHelper.isValid(convertView, type)) {
				// do nothing, use cache...
			} else {
				convertView = newView(position, parent);
			}
            
            //cache the convertView for type...
            if(!mHelper.contains(convertView)){
            	mHelper.put(convertView, getItemViewType(position));
            }
			

		} else {
			// Type都一样
			if (convertView == null) {
				convertView = newView(position, parent);
			} else {
				// do nothing...use cache...
			}
		}
		// bind view
		bindView(position, convertView);
		// return the new view
		return convertView;
	}
    
	abstract void bindView(int position, View parent);

	abstract View newView(int position, ViewGroup parent);

}
